package com.qqt.csr.im.mq;

import com.corundumstudio.socketio.SocketIOClient;
import com.qqt.csr.common.utils.JsonUtil;
import com.qqt.csr.im.entity.mq.MqMessage;
import com.qqt.csr.im.service.EventMsgProducerService;
import com.qqt.csr.im.socketio.constants.EventsConstants;
import com.qqt.csr.im.socketio.utils.SocketIOLocalCacheUtil;
import com.qqt.csr.im.utils.ServiceHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

/**
 * @Date: 2024/10/18 19:25
 * @Description: 新会话创建通知
 **/
@Slf4j
@Service
@RocketMQMessageListener(
        consumerGroup = "${rocketmq.consumer.group}" + "_" + EventsConstants.NEW_CONVERSATION_EVENT,
        topic = EventMsgProducerService.EVENT_FORWARD_TOPIC,
        selectorType = SelectorType.TAG,
        selectorExpression = EventsConstants.NEW_CONVERSATION_EVENT,
        messageModel = MessageModel.BROADCASTING,
        tlsEnable = "${rocketmq.consumer.tlsEnable}"
)
public class NewConversationEventListener implements RocketMQListener<MqMessage> {

    @Override
    public void onMessage(MqMessage data) {
        if (ServiceHelper.INSTANCE.getServiceNode() == null) {
            return;
        }
        // 过滤服务id
        if (!data.getServiceId().equals(ServiceHelper.INSTANCE.getServiceNode().getId())) {
            return;
        }

        // 通知
        SocketIOClient client = SocketIOLocalCacheUtil.getClient(data.getDeviceKey());
        if (client == null || !client.isChannelOpen()) {
            log.info("socket已断开连接，推送消息失败！key:{}", data.getDeviceKey());
            return;
        }

        try {
            client.sendEvent(EventsConstants.NEW_CONVERSATION_EVENT, data.getEventData());
        } catch (Exception e) {
            log.error("socket推送新会话创建通知消息失败！data:{}", JsonUtil.toJson(data));
        }
    }
}
